package edu.nf.vrs.app.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import edu.nf.vrs.app.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.nf.vrs.authenticate.inf.UserTokenService;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Author: @Wai
 * Date: 2022-4-12
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";

    @DubboReference(interfaceClass = UserTokenService.class,check = false)
    private UserTokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) return true;
        String token = request.getHeader(TOKEN_HEADER);
        if (token != null) {
            try {
                String jwt = token.replace(TOKEN_PREFIX, "");
                tokenService.verify(jwt);
                request.setAttribute("uid",tokenService.getPayload(token,"uid",Integer.class));
                return true;
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                responseView(response, "会话已失效");
                return false;
            }
        }
        responseView(response, "请先登陆");
        return false;
    }

    private void responseView(HttpServletResponse response, String message) throws IOException {
        ResultVO vo = new ResultVO();
        vo.setCode(HttpStatus.UNAUTHORIZED.value());
        vo.setMsg(message);
        response.setContentType("application/json;charset=utf-8");
        String json = new ObjectMapper().writeValueAsString(vo);
        response.getWriter().println(json);
    }
}
